package com.xiaohui.user.websocket;

import com.xiaohui.websocket.config.WebSocketServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint(value = "/xh/websocket", configurator = WebSocketServerConfig.class)
@Component
@Slf4j
public class XHWebSocket {

    /**
     * 在线人数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 连接用户
     */
    private static Map<String, XHWebSocket> clients = new ConcurrentHashMap<>();

    /**
     * 某一会话
     */
    private Session session;

    /**
     * 用户唯一标识
     */
    private String erp = "";

    /**
     * 打开连接
     */

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) throws IOException {
        Map<String, Object> userProperties = config.getUserProperties();
        erp = (String) userProperties.get("erp");
        this.session = session;
        this.erp = erp;
        // 断开连接
        if(clients.containsKey(erp)){
            clients.get(erp).session.close();
            onlineCount.decrementAndGet();
            clients.remove(this.erp);
        }
        onlineCount.incrementAndGet();
        clients.put(this.erp, this);
        log.info("用户:{},连接成功,当前连接数:{}", erp, onlineCount.get());
        sendMessage("连接成功", session);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("服务端收到客户端:{},发送消息:{}", erp, message);
        //心跳机制
        if (message.equals("ping")) {
            this.sendMessage("pong", session);
        }
    }

    @OnClose
    public void onClose() throws IOException {
        if(clients.containsKey(this.erp)){
            clients.get(this.erp).session.close();
            clients.remove(this.erp);
            onlineCount.decrementAndGet();
            log.info("用户:{},断开连接,当前连接数:{}", erp, onlineCount.get());
        }
    }

    @OnError
    public void onError(Session session, Throwable error) throws Exception{
        log.error("用户:{},连接异常:{}", erp, error.getMessage());
        session.close();
    }

    /**
     * 指定发送消息
     */
    public void sendMessage(String message, Session session) {
        log.info("服务端给客户端[{}]发送消息{}", this.erp, message);
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("{}发送消息发生异常，异常原因{}", this.erp, message);
        }
    }


    /**
     * 群发
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        for(Map.Entry<String, XHWebSocket> entry : clients.entrySet()){
            String erp = entry.getKey();
            XHWebSocket socket = entry.getValue();
            Session session = socket.session;
            log.info("服务端给客户端:{},发送消息:{}", erp, message);
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("{}发送消息发生异常，异常原因{}", this.erp, message);
            }

        }
    }





}
